<template>
    <Modal v-model:open="notifyModalVisible" width="50%" title="通知设置：" @ok="handleSaveModal" @cancel="handleCancelModal"
        :closable="false" :maskClosable="false" labelAlign="left">

        <Form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
            <Form.Item label="开启通知" name="isEnable">
                <Switch v-model:checked="formState.isEnable" />
            </Form.Item>
            <Form.Item label="通知种类" name="type">
                <Select v-model:value="formState.type" placeholder="请选择通知种类">
                    <Select.Option value="DINGDING">钉钉</Select.Option>
                    <Select.Option value="LARK">飞书</Select.Option>
                    <Select.Option value="WEIXIN">企业微信</Select.Option>
                    <Select.Option value="">空</Select.Option>
                </Select>
            </Form.Item>
            <Form.Item label="安全设置" v-if="formState.type === 'DINGDING' || formState.type === 'LARK'" :required="formState.type === 'DINGDING'"
                name="safeMode">
                <div>
                    <Checkbox v-model:checked="customKeywords" @change="securitySettingChange('CUSTOM_KEYWORDS')">自定义关键字
                    </Checkbox>
                    <div v-if="customKeywords">
                        <Form.Item label="" name="customKeywords">
                            <div class="flex items-center" v-for="(item, index) in addCustomKeywords" :key="index">
                                <Input class="m-t-3" v-model:value="item.keyword" placeholder="请输入自定义关键字" />
                                <MinusCircleOutlined class="text-red m-l-3 m-t-3"
                                    @click="handleRemoveCustomKeywords(index)" />
                            </div>
                        </Form.Item>

                        <div class="m-t-3 m-b-3 flex">
                            <div @click="handleAddCustomKeywords" style="cursor: pointer;">
                                <PlusCircleOutlined class="text-blue" />
                                <span class="text-blue m-l-1">添加</span>
                            </div>
                            <span class="text-gray">（最多添加10个）</span>
                        </div>
                    </div>
                </div>
                <div>
                    <Checkbox v-model:checked="secret" @change="securitySettingChange('SECRET')">加签</Checkbox>
                    <Form.Item label="" name="secret" v-if="secret">
                        <Input class="m-t-3" v-model:value="formState.secret" placeholder="请输入密钥" />
                    </Form.Item>

                </div>
            </Form.Item>
            <Form.Item label="生效模式" name="effectiveMode">
                <Checkbox.Group v-model:value="formState.effectiveMode" :options="effectiveModeOptions">
                </Checkbox.Group>
            </Form.Item>
            <Form.Item label="发送url(webhook)" name="webhook">
                <Input v-model:value="formState.webhook" placeholder="请输入url(webhook)" />
            </Form.Item>
            <Form.Item label="邮件通知" name="email">
                <Input v-model:value="formState.email" placeholder="多个用“,”分割" />
            </Form.Item>
        </Form>
    </Modal>
</template>
<script lang="ts" setup  generic="T extends object">
import { ref } from 'vue';
import type { Rule, RuleObject } from 'ant-design-vue/es/form';
import { Modal, Form, Select, Input, Checkbox, Switch } from 'ant-design-vue'
import type { NotifyFormState } from '~/types/apis/project'
import {
    PlusCircleOutlined,
    MinusCircleOutlined
} from '@ant-design/icons-vue'

const notifyModalVisible = defineModel<T[]>('modalVisible', { required: true })



const emits = defineEmits<{
  (e: 'cancel'): void
  (e: 'submit', value: NotifyFormState): void
}>()

const props = withDefaults(
    defineProps<{
        formData: NotifyFormState
    }>(),
    {
    },
)

watch(() => props.formData, () => {
    if (Object.keys(props.formData).length > 0 && props.formData.id != null) {
        formState.value = {
            isEnable: props.formData.isEnable,
            type: props.formData.type,
            effectiveMode: [],
            webhook: props.formData.webhook,
            email: props.formData.email,
            customKeywords: props.formData.customKeywords,
            secret: props.formData.secret,
            safeMode: props.formData.safeMode,
        }
        if (props.formData.effectiveMode === 'ALL') {
            formState.value.effectiveMode = ['手动执行', '定时执行']
        } else if (props.formData.effectiveMode === 'MANUAL') {
            formState.value.effectiveMode = ['手动执行']
        } else if (props.formData.effectiveMode === 'JOB') {
            formState.value.effectiveMode = ['定时执行']
        }
        if (props.formData.id) {
            formState.value.id = props.formData.id
        }

        if ((props.formData.type === 'DINGDING' || props.formData.type === 'LARK') && formState.value.customKeywords !== '') {
            addCustomKeywords.value = []
            formState.value.customKeywords.split(',').map((item: string) => {
                addCustomKeywords.value.push({
                    keyword: item,
                })

            })
        }
    }
}, {
    deep: true,
})


const customKeywords = computed(() => {
    if (formState.value?.safeMode) {
        return formState.value.safeMode.includes('CUSTOM_KEYWORDS')
    } else {
        return false
    }
})


const secret = computed(() => {
    if (formState.value?.safeMode) {
        return formState.value.safeMode.includes('SECRET')
    } else {
        return false
    }
})

const formRef = ref();
const labelCol = { span: 5 };
const wrapperCol = { span: 13 };
const effectiveModeOptions = ['手动执行', '定时执行']
const addCustomKeywords = ref([])
const formState = ref<NotifyFormState>({
    isEnable: true,
    type: '',
    effectiveMode: ['手动执行', '定时执行'],
    webhook: '',
    email: '',
    customKeywords: '',
    secret: '',
    // 安全设置选择的模式(NONE: 无（都不选默认）;  CUSTOM_KEYWORDS: 自定义关键字; SECRET: 加签) 多个用","分割
    safeMode: '',
});

let validateCustomKeywords = async (rule: RuleObject, value: string) => {
    if (customKeywords && addCustomKeywords.value[0].keyword === '') {
        return Promise.reject('请输入自定义字段');
    }
    else {
        return Promise.resolve();
    }
};

let validateSecret = async (rule: RuleObject, value: string) => {
    if (secret && (value === '' || value === null)) {
        return Promise.reject('请输入密钥');
    } else {
        return Promise.resolve();
    }
};

const rules: Record<string, Rule[]> = {
    isEnable: [
        { required: true, message: '请选择是否开启通知', trigger: 'change' },
    ],
    type: [
        { required: true, message: '请选择通知种类', trigger: 'change' },
    ],
    effectiveMode: [{ required: true, message: '请选择生效模式', trigger: 'change' }],
    webhook: [{ required: true, message: '请输入webhook', trigger: 'blur' }],
    email: [{ required: false, message: '请输入email', trigger: 'blur' }],
    customKeywords: [{ validator: validateCustomKeywords, trigger: 'blur' }],
    secret: [{ validator: validateSecret, trigger: 'blur' }],
    safeMode: [{ message: '请选择安全设置', trigger: 'change' }],

};

const handleSaveModal = () => {
    formRef.value
        .validate()
        .then(() => {
            if (formState.value.type !== 'DINGDING' && formState.value.type !== 'LARK') {
                formState.value.safeMode = 'NONE'
                formState.value.customKeywords = ''
                formState.value.secret = ''
            } else {
                if (!formState.value.safeMode.includes('CUSTOM_KEYWORDS')) {
                    formState.value.customKeywords = ''
                    addCustomKeywords.value = []
                } else {
                   const list =  addCustomKeywords.value.filter((item: { keyword: string }) => item.keyword !== '' && item.keyword)
                   formState.value.customKeywords = list.map((item: { keyword: string }) =>  item.keyword).join(',')
                }
                if (!formState.value.safeMode.includes('SECRET')) {
                    formState.value.secret = ''
                }
            }
            if (formState.value.effectiveMode.length === 2) {
                formState.value.effectiveMode = 'ALL'
            } else if (formState.value.effectiveMode[0] === '手动执行') {
                formState.value.effectiveMode = 'MANUAL'
            } else {
                formState.value.effectiveMode = 'JOB'
            }
            emits('submit', formState.value)
            handleCancelModal()
        })
        .catch(error => {
            console.log('error', error);
        });
};

const handleCancelModal = () => {
    formRef.value.resetFields()
    addCustomKeywords.value = []
    formState.value = {
        isEnable: true,
        type: '',
        effectiveMode:  ['手动执行', '定时执行'],
        webhook: '',
        email: '',
        customKeywords: '',
        secret: '',
        safeMode: '',
    }

    emits('cancel')

}


const securitySettingChange = (keyword: string) => {
    let safeMode = formState.value?.safeMode ? formState.value.safeMode.split(',') : []
    if (formState.value?.safeMode && formState.value.safeMode.includes(keyword)) {
        safeMode = safeMode.filter((item: string) => item !== keyword)
    } else {
        if (keyword === 'CUSTOM_KEYWORDS' && addCustomKeywords.value.length === 0) {
            handleAddCustomKeywords()
        }
        safeMode.push(keyword)
    }
    formState.value.safeMode = safeMode.join(',')
}

const handleAddCustomKeywords = () => {
    addCustomKeywords.value.push({
        keyword: ''
    })
}

const handleRemoveCustomKeywords = (index: number) => {
    if (addCustomKeywords.value.length === 1) return;
    addCustomKeywords.value.splice(index, 1)
}

</script>
